import React from "react";
import _ from "lodash";
import styles from "./WheelSurf.less";
import classnames from "classnames";
import request from "../utils/request";
import { Toast } from "antd-mobile";
import { connect } from "dva";

const toRad = x => {
  return (Math.PI / 180) * x;
};

const random = (min, max) => {
  return Math.floor(Math.random() * (max - min + 1)) + min;
};

class WheelSurf extends React.Component {
  constructor() {
    super();

    this.state = {
      H: 0,
      angles: [],
      card_id: "",
      shopId: "",
      status: false, //是否开启大转盘,
      result: "",
      times: 0,
      isShow: false, //奖品弹出层
      isWin: false, //奖品弹出层
      deg: 0,
      ana: true,
      term: 0,
      isAcc: false,
      prize: [
        {
          pid: 1,
          background_img: 'item3.png',
          active: false
        },
        {
          pid: 2,
          title: '谢谢参与',
          active: false
        },
        {
          pid: 3,
          title: '5个栗子',
          active: false
        },
        {
          pid: 4,
          background_img: 'item1.png',
          active: false
        },
        {
          pid: 5,
          title: '谢谢参与',
          active: false
        },
        {
          pid: 6,
          title: '5个栗子',
          active: false
        },
        {
          pid: 7,
          title: '谢谢参与',
          active: false
        },
        {
          pid: 8,
          background_img: 'item3.png',
          active: false
        },
        {
          pid: 9,
          title: '谢谢参与',
          active: false
        },
        {
          pid: 10,
          title: '3个栗子',
          active: false
        },
        {
          pid: 11,
          title: '5个栗子',
          active: false
        },
        {
          pid: 12,
          title: '3个栗子',
          active: false
        },
      ]
    };
  }

  reset() {
    this.setState(
      {
        isShow: false,
        isWin: false,
        isClick: false,
        resultIndex: -1,
        deg: 0,
        ana: false
      },
      () => {
        this.setState({
          ana: true
        });
      }
    );
  }

  //----------------------- 设置图案 -----------------------------
  setWheel() {
    if (this.state.angles.length <= 0) {
      return;
    }

    let angleDeg = 360 / this.state.angles.length;
    let H = (this.refs.container.clientWidth * 0.88) / 2;
    let D = Math.tan(toRad(angleDeg / 2)) * H * 2;

    this.setState({
      H: H,
      D: D,
      isClick: false,
      resultIndex: -1,
      deg: 0,
      angleDeg: angleDeg
    });

    let self = this;

    console.log("ref", this.refs);

    this.refs.wheel.addEventListener(
      "webkitTransitionEnd",
      function() {
        console.log("动画完毕");
        setTimeout(() => {
          self.setState({
            isShow: true
          });
        }, 300);
      },
      false
    );
  }

  componentDidMount() {
    let self = this;
    let { shopId, card_id } = this.props.location.query;

    // 15815505815
    card_id = '16805167202'
    // 000001
    shopId = 'sixun_000153'

    request("/bigWheel/" + shopId, {
      params: {
        card_id
      },
      method: "get"
    }).then(res => {
      if (res.data.success === true) {
        let items = res.data.data.items;
        let angle = [];
        console.log('可剩余的抽奖', res.data)
        for (let item of items) {
          angle.push({
            ...item
          });
        }

        self.setState(
          {
            shopId: shopId,
            card_id: card_id,
            angles: angle,
            /* 抽奖次数 res.data.times*/
            times: res.data.times,
            term: res.data.data.term,
            isAcc: res.data.data.isAcc
          },
          /* () => {
            self.setWheel();
          } */
        );
      } else {
        //请求失败
        Toast.info("网络繁忙，请稍后重试", 2);
      }
    });
  }

  /**
   * 处理抽奖
   */
  handleOnClick = () => {

    if (this.state.times <= 0) {
      Toast.info("抽奖次数已经用完，欢迎下次继续", 3);
      return;
    }

    if (this.state.isClick) {
      return;
    }

    let self = this;

    this.setState({
      isClick: true
    });

    /* 抽奖动画 */
    const {prize} = this.state
    let index = 0
    let tid = setInterval( ()=> {
      prize.forEach( (v, i) => i === index ? v.active = true :  v.active = false)
      if (index == 0) {
        index = 1
      }else if (index == 1) {
        index = 2
      }else if (index == 2) {
        index = 3
      }else if (index == 3) {
        index = 5
      }else if (index == 5) {
        index = 7
      }else if (index == 7) {
        index = 11
      }else if (index == 11) {
        index = 10
      }else if (index == 11) {
        index = 10
      }else if (index == 10) {
        index = 9
      }else if (index == 9) {
        index = 8
      }else if (index == 8) {
        index = 6
      }else if (index == 6) {
        index = 4
      }else {
        index = 0
      }

      this.setState({
        prize
      })
    },100)

    // 请求后台抽奖数据
    request("/bigWheel", {
      method: "get",
      params: {
        shopId: this.state.shopId,
        card_id: this.state.card_id
      }
    }).then(res => {
      console.log("result中奖数据", res);

       // 模拟数据
       /* res.data = {
          imageUrl: null,
          name: '口红',
          percent: 100,
          prizeCount: 999985,
          success: true,
          tartget: "000280",
          targetType: 1,
          _id: '2354345'
       } */
      if (1) {

        self.setState(
          {
            result: res.data
          },
          () => {
            let target = self.state.result.target;
            let index2 = 0;
            for (let i = 0; i < self.state.angles.length; i++) {
              if (target === self.state.angles[i].target) {
                index2 = i;
                break;
              }
            }

            //开奖啦
            // let initDeg = random(0, 360);
            let resultIndex = this.state.angleDeg * index2;
            let times = random(2, 8) * 4;
            let deg = times * 360 + 90 + resultIndex;

            let nextTimes = this.state.times - 1;

            //////////////// 模态框的设置 ////////////
            let isWin = self.state.result.target !== "0";
            console.log('self.state.result.target', isWin)
            // 清除抽奖动画
            setTimeout(() => {
              clearInterval(tid)
              this.setState({
                isClick: true,
                resultIndex: index2,
                deg: deg,
                times: nextTimes,
                isShow: true,
                isWin: isWin
              });
            }, 1000 * random(2, 4))
            
          }
        );


      } else {
        Toast.info("网络繁忙，请稍后重试", 2);
      }
    });
  };
  
  /* 奖品item */
  pItem = (arr) =>{
      let newArr = arr.map(v => {
        return (
          <div key={v.pid} className={classnames({
            [styles['pItem']]: true,
            [styles['active']]: v.active ? true : false
          })}
          >
            {v.background_img && <img src={require('../assets/wheel/new/'+v.background_img)}/>}
            {
              v.title && <div className={styles['pTitle']}>
                {v.title}
              </div>
            }
          </div>
        )
      })

      return newArr
  }
  render() {
    let angle = [];

    for (let i = 0; i < this.state.angles.length; i++) {
      let name = "",
        icon;

      if (this.state.angles[i].targetType === 0) {
        name = "未中奖";
        icon = (
          <div
            className={styles["ta-content"]}
            style={{
              left: "-" + this.state.H / 1.5 + "px",
              top: "-" + this.state.H * 0.08 + "px"
            }}
          >
            <img
              src={require("../assets/wheel/unluck.png")}
              style={{ width: ".5rem" }}
            />
          </div>
        );
      } else if (this.state.angles[i].targetType === 1) {
        // name = "优惠券";
        name = this.state.angles[i].name;
        icon = (
          <div
            className={styles["ta-content"]}
            style={{
              left: "-" + this.state.H / 1.3 + "px",
              top: "-" + this.state.H * 0.08 + "px"
            }}
          >
            <img src={require("../assets/wheel/coupon-logo.png")} />
          </div>
        );
      } else if (this.state.angles[i].targetType === 2) {
        name = this.state.angles[i].name;
        icon = (
          <div
            className={styles["ta-content"]}
            style={{
              left: "-" + this.state.H / 1.4 + "px",
              top: "-" + this.state.H * 0.13 + "px"
            }}
          >
            <img
              className={styles["ta-gift"]}
              src={require("../assets/wheel/gift.png")}
            />
          </div>
        );
      }

      let leftDelta = 1.05;

      if (name.length >= 6) {
        leftDelta = 0.9;
      } else if (name.length == 5) {
        leftDelta = 0.95;
      }

      angle.push(
        <Triangle
          key={"angle-" + i}
          H={this.state.H}
          D={this.state.D}
          rotate={i * this.state.angleDeg}
          color={i % 2 ? "#fcf9f0" : "#ffdeab"}
        >
          <div
            className={styles["ta-content"]}
            style={{
              left: "-" + this.state.H / leftDelta + "px",
              top: "-" + this.state.H * 0.04 + "px"
            }}
          >
            {name}
          </div>

          {icon}
        </Triangle>
      );
    }

    let size = this.props.size;

    size = document.body.clientWidth * 0.88;

    let comment = [];
    let ii = 1;

    if (this.state.term > 0) {
      comment.push(<div className={styles["x-s-x-s"]}>
        {ii++}、单笔消费满 {this.state.term} 元可获得抽奖一次
        {this.state.isAcc && "，次数可叠加"}。
      </div>);
    }


    comment.push(<div className={styles["x-s-x-s"]}>
      {ii++}、奖品在“电子会员卡” - “优惠券” 里查看。
    </div>);

    comment.push(
      <div className={styles["x-s-x-s"]}>{ii++}、实物奖品凭券码到店领取。</div>
    );


    if (this.state.angles.length > 0) {
      return (
        <div className={styles['wheelWrap']}>
          <div className={styles["wheel-header"]} ref="xxs">
            <img src={require("../assets/wheel/new/header.png")} alt="header" 
              style={{width: '8.816425rem', height: '2.801932rem'}}
            />
          </div>
          <div
            className={styles["wheel-oooo"]}
            /* style={{
              backgroundImage: "url(" + require("../assets/wheel/bg.jpg") + ")"
            }} */
          >
            <div
              className={classnames({
                [styles["wheel-wrapper"]]: true
              })}
              style={{
                width: '100%',
                height: '11.15942rem'
              }}
              ref="container"
            >
              {/* 抽奖次数 */}
              <div
              className={styles["wheel-text-helper"]}
            >
              您还有
                {this.state.times}
              次抽奖机会
            </div>

              <img
                className={styles["wheel-pointer"]}
                src={require("../assets/wheel/new/click.png")}
                onClick={this.handleOnClick}
              />
              
              {/* 奖池 */}
              <div
                className={classnames({
                  [styles["wheel-rotate-container"]]: true,
                  // [styles["ana"]]: this.state.ana  动画过渡3.6s
                })}
                style={{
                  backgroundImage:
                    "url(" + require("../assets/wheel/new/wheel_core.png") + ")",
                    // transform: `rotate(${this.state.deg + "deg"})`
                }}
                ref="wheel"
              >
                <div
                  className={styles["wheel-rotate-wrapper"]}
                  /* style={{
                    width: this.state.H * 2,
                    height: this.state.H * 2
                  }} */
                >
                  {/* {angle} */}
                  {/* 奖品 */}
                  {this.pItem(this.state.prize)}
                </div>

              </div>
              {/* //奖池 */}


            </div>
          </div>
          {/* ---------------------------- */}

          <div
            className={styles["wheel-bg1"]}
           /*  style={{
              backgroundImage: "url(" + require("../assets/wheel/bg2.jpg") + ")"
            }} */
          >


            <div className={styles["btn-group"]}>
              {/* <div
                className={styles["wheel-btn"]}
                style={{
                  backgroundImage:
                    "url(" + require("../assets/wheel/btn-bg.png") + ")"
                }}
              >
                活动规则
              </div> */}

              <div
                className={styles["wheel-btn"]}
                style={{
                  backgroundImage:
                    "url(" + require("../assets/wheel/new/return_index.png") + ")"
                }}
                onClick={ ()=> {
                  this.props.history.replace(`/third_vipCard?shopId=${this.state.shopId}`)
               }}
              >
                返回首页
              </div>

              <div className={styles["xxxx-s"]}>
                <div className={styles["x-s-x-s"]}>活动说明：</div>
                {/* ---------------------------------------------------------------------------------------*/}
                {_.map(comment, v => v)}
              </div>
            </div>
          </div>
         
          
          {/* 弹出层 */}
          <div
            className={classnames({
              [styles["bg-out-container"]]: true,
              // this.state.isShow
              [styles["show"]]: this.state.isShow
            })}
          >
            <div
              className={styles["bg-out-render"]}
              onClick={this.closeModal}
            />

            {/* 奖品内容 */}
            <div
              className={classnames({
                [styles["bg-out-modal"]]: true,
                [styles["show"]]: this.state.isShow
              })}

              style={{
                background: "url(" +require('../assets/wheel/new/redPacket.png')+ ")",
                height: '9.082126rem',
                width: '7.777778rem'
              }}
            >
              {/* 1 */}
              <div className={styles["bg-out-content"]}>
                <div className={styles["modal-text-1"]}>
                  {!this.state.isWin && (
                    <img
                      className={styles["m-logo"]}
                      src={require("../assets/wheel/unluck.png")}
                    /> 
                  )}

                  {this.state.isWin && (
                    <div 
                      className={styles["m-logo"]}
                      style={{
                        background: 'url('+ require("../assets/wheel/new/coupon_bg.png") + ') no-repeat 0 0',
                        backgroundSize: '100% 100%'
                       }}
                    >
                      <sapn>优惠券</sapn>
                    </div>
                  )}

                  <span className={styles["m-t"]}>
                    {!this.state.isWin && "好可惜，差点就中了"}
                    {this.state.isWin && 
                      (<div className={styles['shot']}>
                        <span>恭喜你</span>
                        <span>抽中{this.state.result.name}</span>
                      </div>)}
                  </span>
                </div>
              </div>

              {/* 2 */}
              <div className={styles["bg-out-content"]}>
                <div className={styles["modal-text-1"]}>
                  <span className={styles["m-t2"]}>
                    {!this.state.isWin && "好遗憾，没中奖，一定是姿势不对~"}
                    {this.state.isWin && "可在”电子会员卡-优惠券“查看"}
                  </span>
                </div>
              </div>

              {/* 3 */}
              <div className={styles["bg-out-content"]}>
                <div className={styles["modal-text-1"]}>
                  {/* {this.state.times > 0 && (
                    <span className={styles["m-t3"]}>
                      你还有
                      {this.state.times}
                      次机会
                    </span>
                  )} */}

                  <div
                    className={styles["m-t4"]}
                    onClick={this.closeModal}
                  >
                    返回抽奖
                  </div>
                </div>
              </div>
            </div>
            
          </div>
        </div>
      );
    } else {
      return <div />;
    }
  }

  closeModal = () => {
    this.setState({
      isShow: false
    });

    this.reset();
  };
}

class Triangle extends React.Component {
  constructor() {
    super();

    this.state = {
      H: 0,
      D: 0,
      top: 0,
      left: 0,
      rotate: 0,
      color: "gold"
    };
  }

  componentWillReceiveProps(nextProps) {
    this.setState({
      H: nextProps.H,
      D: nextProps.D,
      rotate: nextProps.rotate,
      color: nextProps.color
    });
  }

  render() {

    let H = this.state.H;
    let D = this.state.D;
    let ang = toRad(this.state.rotate);

    let left = 0.5 * H - 0.5 * H * Math.cos(ang);
    let top = H + Math.sin(ang) * 0.5 * H - 0.5 * D;

    return (
      <div className={styles['wheelWrap2']}>
      <div
        className={styles["wheel-triangle"]}
        /* style={{
          borderLeftWidth: this.state.H + "px",
          borderTopWidth: this.state.D / 2 + "px",
          borderBottomWidth: this.state.D / 2 + "px",
          borderLeftColor: this.state.color,
          top: top,
          left: left,
          transform: "rotate(-" + this.state.rotate + "deg)"
        }} */
      >
        {this.props.children}
      </div>
      </div>
    );
  }
}

export default connect()(WheelSurf);
